/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestInt.controlador;

import gestInt.DAO.ArticuloJpaController;
import gestInt.DAO.PublicacionJpaController;
import gestInt.DAO.exceptions.RollbackFailureException;
import gestInt.modelo.Articulo;
import gestInt.modelo.ArticuloPK;
import gestInt.modelo.Publicacion;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author elkin
 */
@Named(value = "articuloManagedBean")
@SessionScoped
public class ArticuloManagedBean implements Serializable {

    @Resource
    private UserTransaction utx;

    private Articulo objArticulo;
    private Publicacion objTraGra;
    private final ArticuloJpaController jpaArticulo;
    private final PublicacionJpaController jpaTraGra;
    private List<Articulo> lstArticulos;
    private List<Publicacion> lstTraGra;
    boolean encontrado;
    
    private final String destino = "/home/elkin/Escritorio/ultimo/GestInt/web/pdf/";
    private UploadedFile file;
    /**
     * Creates a new instance of ArticuloManagedBean
     */
    public ArticuloManagedBean() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("GestIntPU");
        this.objArticulo = new Articulo();
        this.jpaArticulo = new ArticuloJpaController(utx, emf);
        this.encontrado = false;
        this.lstArticulos = this.jpaArticulo.findArticuloEntities();
        this.jpaTraGra = new PublicacionJpaController(utx, emf);
    }
    
    public void agregarArticulo() {
        
        ArticuloPK prikey = new ArticuloPK();
        prikey.setIdarticulo(2);
        prikey.setIdpublicacion(1);
        
        this.objArticulo.setArticuloPK(prikey);
        this.objTraGra = this.jpaTraGra.findPublicacion(1);
        this.objArticulo.setPublicacion(objTraGra);
        this.objArticulo.setNombre(getFile().getFileName());
        
        try {
            this.jpaArticulo.create(objArticulo);
        } catch (RollbackFailureException ex) {
            Logger.getLogger(ArticuloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ArticuloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        this.upload();
    }

    public Articulo getObjArticulo() {
        return objArticulo;
    }

    public void setObjArticulo(Articulo objArticulo) {
        this.objArticulo = objArticulo;
    }

    public List<Articulo> getLstArticulos() {
        return lstArticulos;
    }

    public void setLstArticulos(List<Articulo> lstArticulos) {
        this.lstArticulos = lstArticulos;
    }
    
    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void transferFile(String fileName, InputStream in) {
        try {
            OutputStream out = new FileOutputStream(new File(destino + fileName));
            int reader = 0;
            byte[] bytes = new byte[(int) getFile().getSize()];
            while ((reader = in.read(bytes)) != -1) {
                out.write(bytes, 0, reader);
            }
            in.close();
            out.flush();
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ArticuloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ArticuloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void upload() {
        String extValidate;
        if (getFile() != null) {
            String ext = getFile().getFileName();
            if (ext != null) {
                extValidate = ext.substring(ext.indexOf(".") + 1);
            } else {
                extValidate = null;
            }

            if (extValidate.equals("pdf")) {
                try {
                    transferFile(getFile().getFileName(), getFile().getInputstream());
                } catch (IOException ex) {
                    Logger.getLogger(ArticuloManagedBean.class.getName()).log(Level.SEVERE, null, ex);
                    FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null, new FacesMessage("Error", "Error al subir"));
                }
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Correcto", "Agregado Correctamente"));
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null,new FacesMessage("Error extencion", "solamente .PDF"));
            }
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null,new FacesMessage("Error", "seleccione un archivo"));
        }
    }
    
}
